<?php
/**
 * 视频
 */
namespace app\stream\controller;
use app\common\controller\ZhiboV2;
class Video extends ZhiboV2{
    protected $mod = '';
    /**
     * @name 初始化方法
     * @author martinsun syh@sunyonghong.com
     */
    protected function _initialize(){
        //调用父类进行权限检测
        parent::_initialize();
        $this->mod = model('stream/Video');
    }

    /**
     * @name 未定的接口
     * @return array 
     */
    public function _empty($action){
        if(strtolower(substr($action, 0, 3)) == 'get'){
            //权限检测
            $auth = self::checkApi();
            if($auth !== true) return $this->api_info;
            if($this->user_id){
                $uid = $this->user_id;
            }else{
                //取得UID
                $uid = self::parseName(substr($action,3))[0];
            }
            if($uid){
                $uid = decrypt_id($uid);
                $st = model('open/User')->hasUser(['uid' => $uid]);
                if($st === true){
                    $this->data['order'] = 'own';
                    $this->user_id = $uid;
                    return $this->getList($this->data);
                }
            }
            return getApiErrorCode('40007');
        }
        return getApiErrorCode('00404');
    }
    /**
     * @name 获取回放视频的地址
     */
    public function getPlayUrl(){
        $auth = self::checkApi(['vid']);
        if($auth !== true) return $this->api_info;
        $vid = decrypt_id($this->vid);
        $playurl = $this->mod->getPlayUrl($vid);
        if($playurl){
            return ['code'=>'00000','data'=>['playurls'=>['http'=>$playurl, 'shop' => model('stream/StreamShop')->getInstance()->getShopByVideo($vid)]]];
        }
        return getApiErrorCode('40423');
        
    }
    /**
     * @name 获取直播回放
     * @param array $data 过滤的数据信息,筛选条件,提供内部调用
     * @param int limit from api 分页的条数 default:10
     * @return array 结果信息
     */
    public function getList($data = []){
        $auth = self::checkApi();
        if($auth !== true) return $this->api_info;
        $limit = (int)$this->data['limit'] ?: 10;
	$page = $this->p ?: 1;
        if($this->usid){
            $uid = model('open/User')->getUidByUsid($this->usid);
            $this->order = 'own';
        }else{
            $uid = $this->uid;
        }
	$order = $this->order ?:'all';
        
        $map['uid'] = ($order == 'own') ? $uid : ['neq',$uid];
        $map['status'] = 0;
        //筛选
        $map = array_merge($map,self::_getFilterParam());
        $list = $this->mod->getPlayBackList($map,$limit);
	$hub = parent::getHub();
        $stream = $hub->stream($this->usid);
        try {
		$status = $stream->liveStatus();
	} catch ( \Exception $e) {
		$status = false;
	}
	if ($status && $this->p == 1) {
            $streamInfo         = model('stream/Stream')->getstreamInfo($map['uid']);
            $im = model('open/UserImAccount')->getConversation(['uid' => $map['uid'], 'affix' => $this->usid, 'type' => 2], $auto_create);
            $data['online_count'] = $im['mc'] ? (int) $im['mc'] : 0;
            unset($im['mc']);
            $data['im'] = (object) $im;
            $live                   = [
		
                'stream' => [
                    'id' => $this->usid,
                    'title' => $streamInfo['stream_title'] ?: '',
                    'location' => $streamInfo['location'],
                    'icon' => (object)[
                        '0' => $streamInfo['stream_icon'] 
                            ? 
                            model('attach/Attach', ['getAttachUrl', $streamInfo['stream_icon']])['0'] 
                            : 
                            \Qiniu\Pili\SnapshotPlayURL(C('qiniu.snap-shot'), C('qiniu.hub-name'), $this->usid)
                            
                    ],
					'online_count' => 0
                ],
                'im' => (object) $im,
                'user' => [
                    'usid' => $this->usid
                ]
		];
		array_unshift($list, $live);
        }
        return ['code'=>'00000','data'=>$list];
    }
    /**
     * @name 获取直播回放
     * @param array $data 过滤的数据信息,筛选条件,提供内部调用
     * @param int limit from api 分页的条数 default:10
     * @return array 结果信息
     */
    public function getListByOwn(){
        $auth = self::checkApi();
        if($auth !== true) return $auth;
        
        $limit = (int)$this->data['limit'] ?: 10;
        $map['uid'] =   $this->uid ;
        $map['status'] = 0;
        //筛选
        $map = array_merge($map,self::_getFilterParam());
        $list = $this->mod->getPlayBackList($map,$limit);
        return ['code'=>'00000','data'=>$list];
    }

    /**
     * 删除回放
     */
    public function delete()
    {
        $auth = self::checkApi(['vid']);
        if($auth !== true) return $this->api_info;

        $vids = $this->vid;
        $vids = array_filter(array_unique(explode(',', $vids)));
        foreach ($vids as &$vid) {
            $vid = decrypt_id($vid);
        }

        // if (!$this->mod->hasOne(array('vid' => array('in', $vids), 'uid' => $this->uid, 'is_del' => 0))) {
        //     return getApiErrorCode('40423');
        // }

        if(M('video')->where(array('vid' => array('in', $vids)))->save(array('is_del' => 2))) {
            return ['code'=>'00000', 'message' => '删除成功'];
        }

        return getApiErrorCode('70401');
    }
    /**
     * @name 组装筛选条件
     * @map array $map 传递的已有条件
     * @return array $map 最终的筛选条件
     */
    protected function _getFilterParam($map = []){
         //筛选条件处理
        $filter_list = C('filter_list.video');
        foreach($filter_list as $v){
            if($this->data[$v['key']]){
                //带时间的数据单独处理
                if(preg_match('/time/i',$v['key'])){
                    list($start,$end) = explode(',',$this->data[$v['key']]);
                    $start > NOW_TIME && $start = NOW_TIME;
                    $end = ($end > NOW_TIME || !$end ) ? NOW_TIME : $end;
                    $map['save_time'] = ['between',$start.','.$end];
                    continue;
                }
                
                //带时间的地区单独处理
                if(preg_match('/location/i',$v['key'])){
                    if((int)($this->location)){
                        $this->data['location'] = D('Area')->getAreaById($this->data['location'])['title'];
                    }
                    $this->data['location'] && $map['location'] = ['like','%'.$this->data['location'].'%'];
                    continue;
                }
                //带男女
                if(preg_match('/sex/i',$v['key'])){
                    if((int)($this->sex)){
                        $map['sex'] = (int)$this->sex;
                    }elseif(false !== stripos($this->sex,'男')){
                        $map['sex'] = 1;
                    }elseif(false !== stripos($this->sex,'女')){
                        $map['sex'] = 2;
                    }
                    continue;
                }
                $map[$v['key']] = $this->data[$v['key']];
            }
        }
        return $map;
    }
    /**
     * @name 搜索接口
     * @param array $data 内部调用的参数数组
     * @param string keyword from api 搜索的关键字
     * @return array 数据结果
     */
    public function search($data = []){
        $st = self::checkApi();
        if(true !== $st) return $this->api_info;
        $keyword = formatEmoji(string_filter($this->keyword),true);
        $keyword && $map['video_title'] = ['like','%'.$keyword.'%'] ;
        $map['status'] = 0;
        //$map['uid'] = ['neq',$this->uid];
        //条数限制
        $limit = (int)$this->limit ? (int)$this->limit : 10;
        $data = $this->mod->getPlayBackList($map,$limit,"vid desc,locate('".$this->keyword."', video_title) asc,length(video_title)-length('".$this->keyword."')");
        return ['code' => '00000', 'data' => ['video_list'=>$data]];
    }
    
    /**
     * 解析name
     * @param string $name
     * @return array 返回name和类型
     */
    private static function parseName($name)
    {
        return strpos($name, '/') ? explode('/', $name, 2) : [$name];
    }

	/**
     * @name 播放回放
     */
    public function show(){
	    if($this->usid){
		    $this->uid = model('open/User')->getUidByUsid($this->usid);
	    }
	    $vid = decrypt_id($this->vid);
	    $map = [
		    'from_stream' => $this->usid,
		    'uid' => $this->uid,
		    'vid' => $vid,
            'is_del' => 0,
	    ];
	    $video = $this->mod->getOne($map);
	    if ($video) {
		    if (is_numeric($video['video_icon'])) {
			    $video['video_icon'] = model('attach/Attach',['getAttachUrl',$video['video_icon']])[0];
		    } else {
			    $video['video_icon'] = C('qiniu.cdn-url') . '/' . $video['video_icon'];
		    }
		    $video['video_url'] = C('qiniu.cdn-url') . '/' . $video['video_path'];
	    }

	    zbdefine('MODEL_NAME','video');
	    $view = new \think\View([
		    'theme_on' => true,
		    'parse_str' => [
			    '__static__' => '/public/static/stream',
			    '__public__' => '/public/static/public'
		    ]
	    ]);
	    if(strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone')||strpos($_SERVER['HTTP_USER_AGENT'], 'iPad')){
		    // $view->assign('system', 'ios');
		    $view->assign('download', 'https://www.pgyer.com/FPku');
	    }else if(strpos($_SERVER['HTTP_USER_AGENT'], 'Android')){
		    // $view->assign('system', 'android');
		    $view->assign('download', 'https://www.pgyer.com/l2L3');
	    }else{
		    // $view->assign('system', false);
		    $view->assign('download', '');
	    }
	    $view->assign('video', $video);
	    //传递配置信息
	    $config = model('admin/Config')->getConfigValue(['type'=>'stream','key'=>'stream_3gconfig']);
	    $view->assign('config',$config);
	    $uname = getUname($this->uid) ?: 'TA';
	    $view->assign('pageTitle', ($video['video_title'] ? ($video['video_title'] . ' - ' . $uname . '的回放') : ($uname . '的回放')));
	    $view->assign('app_name',$this->app_name);
	    $view->assign('deskicon_ico', getImageUrl($config['app_logo'],4) ?: "/public/static/deskicon.png");
	    $GLOBALS['format'] = 'html';
	    $view->assign('shop', (array) model('stream/StreamShop')->getInstance()->getShopByVideo($vid));

	    return $view->fetch('stream@video/show');
    }
}
